//
//  File.swift
//  
//
//  Created by WeCloudIOS on 2022/4/13.
//

import Foundation
import UIKit

struct Windos {
    static let w = UIScreen.main.bounds.size.width
    static let h = UIScreen.main.bounds.size.height
}

public class RoomListener : UIViewController{
    
    //切换摄像头
    lazy var cameraBtn: UIButton = {
        let btn = UIButton()
        let image = Tool.SCImage(named: "video_change_camera")
        btn.setImage(image, for: .normal)
        btn.tag = 1000
        btn.addTarget(self, action: #selector(tapAction(button:)), for: .touchUpInside)
        return btn
    }()
    
    //切换视图布局
    lazy var changeViewBtn: UIButton = {
        let btn = UIButton()
        let image = Tool.SCImage(named: "check_icon")
        btn.setImage(image, for: .normal)
        btn.addTarget(self, action: #selector(tapAction(button:)), for: .touchUpInside)
        btn.tag = 1001
        return btn
    }()
    let room = WCObservableRoom()
    var controlView: ControlView?
    var controller:UIViewController
    var outTrack: Track?
    var outTrackDefaut: Track?
    var outTrackName: String?
    var trackArray = [Track]()
    var timeLabelView = timeView()
    var didTrackArray = [Track]()
    var listView = VideoListView()
    var defautView = VideoDefaultView()
    var isOur = true
    var cameras = true
    var mutes = true
    var louds = true
    var timer: Timer?
    var count: Int = 0
    @objc public var wurl: String?
    @objc public var wroomId: String?
    @objc public var wtoken: String?
    @objc public var leaveBlock = {(roomId: String) in}
    @objc public var inviteBlock = {(roomId: String) in}
    
    var userlistView = UserListView()
    
    init(_ controller: UIViewController) {
        self.controller = controller
        super.init(nibName: nil, bundle: nil)
    }
    
    
    @objc public convenience init(cv: UIViewController,camera: Bool,mute: Bool,loud: Bool,url: String,roomId: String,token: String) {
        self.init(cv)
        room.room.add(delegate: self)
        self.controlView  = ControlView(cv: self, camera: camera, mute: mute, loud: loud)
        cameras = camera
        mutes = mute
        louds = loud
        wtoken = token
        wurl = url
        wroomId = roomId
        view.addSubview(defautView)
        view.addSubview(controlView!)
        view.addSubview(userlistView)
        view.addSubview(changeViewBtn)
        view.addSubview(cameraBtn)
        view.addSubview(timeLabelView)
        let space = (Int(Windos.w) - 20)/5+45+40
        
        controlView!.listen = self
        controlView!.observable = room
        
        userlistView.defautView = defautView;
        userlistView.room = self
        
        timeLabelView.frame = CGRect(x:(Windos.w-90)/2, y: 45, width: 90, height: 20)
        
        cameraBtn.frame = CGRect(x: Windos.w-55, y: 45, width: 35, height: 35)
        
        controlView!.frame = CGRect(x: 10, y: Int(Windos.h)-space-20, width: Int(Windos.w)-20, height: space)
        
        userlistView.frame = CGRect(x: 0, y: controlView!.frame.origin.y-10, width: Windos.w, height: 0)
        
        changeViewBtn.frame = CGRect(x: 10, y: userlistView.frame.origin.y-50, width: 40, height: 40)
        
        defautView.frame = CGRect(x: 0, y: 0, width: Windos.w, height: Windos.h)
        
        
        self.controller.view.addSubview(self.view)
        self.view.frame = CGRect(x: 0, y: 0, width: Windos.w, height: self.view.frame.size.height)
        
        guard wurl != nil else{
            fatalError("UR不能为为空")
        }
        guard wtoken != nil else{
            fatalError("token不能为为空")
        }
        room.room.connect(wurl!,wtoken!).then { room in
            if self.cameras{
                self.room.toggleCameraEnabled()
            }
            
            if self.mutes{
                self.room.toggleMicrophoneEnabled()
            }
            
        }.catch { error in
            
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public override func viewDidLoad() {
        view.backgroundColor = UIColor.gray
    }
    
    public override func viewWillDisappear(_ animated: Bool) {
        cancelTimer()
    }
    
    func upDateUI() {
        userlistView.frame = CGRect(x: 0, y: controlView!.frame.origin.y-90, width: Windos.w, height: 80)
        changeViewBtn.frame = CGRect(x: 10, y: userlistView.frame.origin.y-50, width: 40, height: 40)
    }
    
    func upDateState() {
        isOur = true
        //重新加视图
        defautView = VideoDefaultView();
        defautView.frame = CGRect(x: 0, y: 0, width: Windos.w, height: Windos.h)
        view.insertSubview(defautView, belowSubview: controlView!)
        
        userlistView.defautView = defautView;
        show()
    }
    
    func back(){
        cancelTimer()
        sendLeaveRoom()
        NotificationCenter.default.post(name: NSNotification.Name("TRTCEXIT"), object: nil)
        let selector = NSSelectorFromString("closeMine")
        if self.controller.responds(to: selector){
            self.controller.perform(selector)
        }else{
            
        }
    }
    
    func closeCamera(close: Bool){
        
        cameras = close
        if !close {
            outTrack = nil
        }else{
            outTrack = outTrackDefaut
        }
    }
    
    func addUser() {
        let selector = NSSelectorFromString("inviteOther:")
        if controller.responds(to: selector){
            
            
            var array:Array = [String]()
            for (_,value) in room.remoteParticipants.elements{
                array.append(value.identity)
            }
            
            controller.perform(selector,with: array)
        }else{
            self.inviteBlock(wroomId!)
        }
    }
    
    func sendLeaveRoom()  {
        leaveBlock(wroomId!)
    }
    
    @objc func tapAction(button: UIButton)->Void{
        
        if button.tag == 1000{
            room.switchCameraPosition()
        }else{
            isOur = false
            listView = VideoListView()
            listView.listen = self
            listView.room = room
            listView.frame = CGRect(x: 0, y: 100, width: Windos.w, height: Windos.h-100)
            view.addSubview(listView)
            show()
            
            defautView.removeFromSuperview()
        }
    }
    
}

//MARK: - RoomDelegate
extension RoomListener: RoomDelegate {

    public func room(_ room: Room, localParticipant: LocalParticipant, didPublish publication: LocalTrackPublication) {
        guard let track = publication.track as? VideoTrack else {
            return
        }
        outTrack = track
        outTrackDefaut = track
        outTrackName = localParticipant.identity
        DispatchQueue.main.async {
            self.show()
        }
    }

    public func room(_ room: Room, participant: RemoteParticipant, didSubscribe publication: RemoteTrackPublication, track: Track) {
        guard let track = track as? VideoTrack else {
            return
        }
        self.trackArray.append(track)
        
        DispatchQueue.main.async {
            self.show()
        }
    }
    
    public func room(_ room: Room, participant: RemoteParticipant, didUnsubscribe publication: RemoteTrackPublication, track: Track){
        if track == outTrack{
            outTrack = nil
        }
        
        DispatchQueue.main.async {
            self.show()
        }
    }
    public func room(_ room: Room, participantDidJoin participant: RemoteParticipant) {
        DispatchQueue.main.async {
            self.show()
        }
    }
    
    public func room(_ room: Room, participantDidLeave participant: RemoteParticipant){
        DispatchQueue.main.async {
            self.show()
        }
    }
    
    public func room(_ room: Room, participant: RemoteParticipant, didPublish publication: RemoteTrackPublication){
        
        DispatchQueue.main.async {
            self.show()
        }
        
    }
    public func room(_ room: Room, participant: RemoteParticipant, didUnpublish publication: RemoteTrackPublication) {
        DispatchQueue.main.async {
            self.show()
        }
    }
    
    public func room(_ room: Room, participant: Participant, didUpdate publication: TrackPublication, muted: Bool) {
        DispatchQueue.main.async {
            self.show()
        }
    }
    
    public func room(_ room: Room, didFailToConnect error: Error){
        print("进入房间失败")
        DispatchQueue.main.asyncAfter(deadline: .now()+1) {
            room.disconnect()
            self.back()
            
        }
    }
    
    public func room(_ room: Room, didConnect isReconnect: Bool){
        print("已连接到房间")
        UserDefaults.standard.set(true, forKey: "isInRoom")
        DispatchQueue.main.asyncAfter(deadline: .now()+1) {
            if self.timer == nil{
                self.initTimer()
            }
            
        }
    }
}

//MARK: - 显示结果
extension RoomListener{
    
    func show() -> Void {
        
        if isOur{
            var sid: String?
            var isNo = false
            var firstUser: ObservableParticipant?
            for (key,value) in room.remoteParticipants.elements{
                if value.firstVideoAvailable{
                    isNo = true
                    if outTrack != nil{
                        defautView.setVideo(track1: outTrack as? VideoTrack, track2:value,outTrackName: outTrackName)
                        sid = key
                    }else{
                        sid = key
                        defautView.setVideo(track1:nil , track2:value,outTrackName:nil)
                    }
                    
                    break
                } else{
                    if firstUser == nil {
                        firstUser = value
                    }
                }
            }
            
            if !isNo{
                if outTrack != nil{
                    defautView.setVideo(track1:outTrack as? VideoTrack , track2:firstUser,outTrackName: outTrackName)
                }else{
                    defautView.setVideo(track1: nil, track2:firstUser,outTrackName: outTrackName)
                }
            }
            
            showUserList(sid: sid)
        }else{
            listView.show()
        }
    }
    
    func showUserList(sid:String?){
        if room.remoteParticipants.count>0{
            userlistView.ObservableRoom = room
            userlistView.show(sid: sid)
            userlistView.frame = CGRect(x: 0, y: controlView!.frame.origin.y-90, width: Windos.w, height: 80)
            changeViewBtn.frame = CGRect(x: 10, y: userlistView.frame.origin.y-50, width: 40, height: 40)
        }else{
            userlistView.ObservableRoom = room
            userlistView.show(sid: sid)
            userlistView.frame = CGRect(x: 0, y: controlView!.frame.origin.y-10, width: Windos.w, height: 0)
            changeViewBtn.frame = CGRect(x: 10, y: userlistView.frame.origin.y-50, width: 40, height: 40)
        }
    }
    
}
//MARK: - 定时器处理
extension RoomListener{
    func initTimer(){
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(recordTime), userInfo: nil, repeats: true)
        if let curTimer: Timer = timer{
            RunLoop.main.add(curTimer, forMode: .common)
        }
    }
    
    @objc func recordTime(){
        count += 1
        timeLabelView.setTime(second: count)
        
        
        
        if count%5 == 0{
            sendHeartbeat()
        }
    }
    
    func cancelTimer(){
        if timer != nil{
            timer?.invalidate()
            count = 0
            timer = nil
        }
    }
    
    func sendHeartbeat()  {
        
        let params:NSMutableDictionary = NSMutableDictionary()
        params["roomId"] = wroomId!
        
        NetWork(url: "/api/multiMeet/heartbeat",params: params) {
            data in
        }
    }
}


//MARK: - 顶部计时器视图

class timeView : UIView{
    
    init() {
        super.init(frame: CGRect.zero)
        setUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUI(){
        backgroundColor = UIColor.init(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 0.4)
        layer.cornerRadius = 10
        
        
        addSubview(redView)
        addSubview(nameLabel)
    }
    
    func setTime(second:Int) {
        nameLabel.text = FormatDate(second: second)
    }
    
    //  second 秒数
    func FormatDate(second:Int) ->String{
        
        let formatter = DateComponentsFormatter.init()
        formatter.zeroFormattingBehavior = .pad
        formatter.allowedUnits = NSCalendar.Unit(rawValue:NSCalendar.Unit.minute.rawValue | NSCalendar.Unit.second.rawValue)
        
        formatter.unitsStyle = DateComponentsFormatter.UnitsStyle.positional
        
        // 结果默认格式为 1m 1s
        var resultStr = formatter.string(from: TimeInterval(second)) ?? ""
        resultStr = resultStr.replacingOccurrences(of: "s", with: "", options: .literal, range: nil)
        resultStr = resultStr.replacingOccurrences(of: "m", with: ":", options: .literal, range: nil)
        
        return resultStr
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        redView.frame = CGRect(x: 10, y: 6, width: 8, height: 8)
        nameLabel.frame = CGRect(x: 18, y: 0, width: frame.size.width-24, height: 20)
    }
    
    //红点背景
    let redView: UIView = {
        let bgView = UIView()
        bgView.layer.cornerRadius = 4
        bgView.backgroundColor = UIColor.red
        return bgView
    }()
    
    //计时文本
    let nameLabel: UILabel = {
        let label = UILabel()
        label.text = "正在连接"
        label.textAlignment = .center
        label.textColor = UIColor.black
        label.font = UIFont.systemFont(ofSize: 14)
        return label
    }()
    
}
